<template>
  <ry-modal :title="`新增客户`" v-model="visible" destroyOnClose :maskClosable="false"
            :confirmLoading="confirmLoading" @ok="handleOk">
    <a-spin :spinning="confirmLoading">
      <a-form-model :model="form" :rules="rules" v-bind="modelConfig">
        <a-row :gutter="[24,0]">
          <a-col :span="24" style="font-weight: 600;margin-bottom: 10px;margin-left: 20px">
            <span style="background-color:#3acaca;margin-right: 4px">&nbsp</span>基础信息
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="客户编码">
              <a-input v-model="form.serialNumber" placeholder="请输入客户编码" type="number"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="姓名" prop="nickname">
              <a-input v-model="form.nickname" placeholder="请输入姓名"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="性别" prop="sex">
              <a-radio-group v-model="form.sex" @change="changeGender">
                <a-radio v-for="item in Gender" :value="item.value" :key="item.label">
                  {{ item.label }}
                </a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="证件类型">
              <a-radio-group @change="changeIdType" default-value="idCard">
                <a-radio value="idCard">身份证</a-radio>
                <a-radio value="otherCard">其他证件</a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if="idCardType">
            <a-form-model-item label="身份证">
              <a-input v-model="form.idCard" placeholder="请输入身份证" @change="idCardChange"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if="!idCardType">
            <a-form-model-item label="其他证件号">
              <a-input v-model="form.idCard" placeholder="请输入其他证件号码"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="用户密码(已加密)" :labelCol="{span:6}" :wrapperCol="{span:8}">
              <a-row type="flex" align="middle">
                <a-col :span="20">
                  <a-input-password v-model="form.mmpd" placeholder="初始密码为自动生成，默认身份证后6位"/>
                </a-col>
                <a-col :span="4" style="padding-left: 8px;">
                  <a-tooltip placement="top" title="重置密码为身份证或其他证件后6位">
                    <a-button size="small" type="primary" @click="resetPassword">重置</a-button>
                  </a-tooltip>
                </a-col>
              </a-row>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="出生年月日">
              <a-date-picker @change="onChangeBirth" v-model="form.birth"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="年龄" :labelCol="{span:6}" :wrapperCol="{span:2}">
              <a-input v-model="form.age" placeholder="选择出生年月日后会自动计算" :disabled="true"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="联系电话">
              <a-input v-model.trim="form.phone" placeholder="请输入您的联系电话"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="近期体检报告">
              <a-checkbox-group v-model="form.medicalReportList" @change="changeMedicalReport">
                <a-checkbox v-for="item in medicalReports" :value="item.value" :key="item.label">
                  {{ item.label }}
                </a-checkbox>
              </a-checkbox-group>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="居住地址" prop="address">
              <a-input v-model="form.address" placeholder="请输入详细地址"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="备注">
              <a-input v-model="form.remake" placeholder="请输入备注"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="客户渠道">
              <a-input v-model="form.source" placeholder="请输入客户渠道"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24" style="font-weight: 600;margin-bottom: 10px;margin-left: 20px;margin-top: 20px">
            <span style="background-color:#3acaca;margin-right: 4px">&nbsp</span>健康报告上传
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="上传文件" prop="reportFiles">
              <div>
                <a-upload list-type="picture" :file-list="fileList"
                    :showUploadList="{ showPreviewIcon: true, showRemoveIcon: true }"
                    :before-upload="beforeUpload" @change="previewFile" @remove="handleRemove" @preview="onPreview">
                  <a-button style="background:#fff;color:#000" :loading="uploadLoading">
                    上传
                  </a-button>
                </a-upload>
              </div>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-spin>
    <a-modal v-model="previewVisible" :footer="null" :width="900">
      <div v-if="previewType === 'image'" style="text-align:center">
        <img :src="previewUrl" alt="预览" style="max-width:100%; max-height:80vh" />
      </div>
      <div v-else-if="previewType === 'pdf'" style="height:80vh">
        <iframe :src="previewUrl" style="width:100%; height:100%; border:0;" />
      </div>
    </a-modal>
  </ry-modal>
</template>

<script>
import {CommonModal} from '@/ryweb'

export default {
  name: '',
  mixins: [CommonModal],
  props: ['url'],
  components: {},
  data() {
    return {
      Gender: [{value: '男', label: '男'}, {value: '女', label: '女'}],
      whether: [{value: '是', label: '是'}, {value: '否', label: '否'}],
      medicalReports: [{value: '血常规', label: '血常规'}, {value: '生化', label: '生化'}, {
        value: '肿瘤标志物',
        label: '肿瘤标志物'
      }, {value: '传染病四项', label: '传染病四项'}],
      previewVisible: false,
      previewUrl: '',
      previewType: '',
      value: [],
      uploadLoading: false,
      disabledType: false,
      idCardType: true,
      fileList: [],
      medicalReportList: [],
      form: {},
      fileUid: 1,
      modelConfig: {
        ref: 'ruleForm',
        labelCol: {span: 6},
        wrapperCol: {span: 14}
      },
      rules: {
        idCard: [{
          required: true,
          message: '请输入证件号码',
          trigger: 'change'
        }, {
          validator: (rule, value, callback) => {
            if (!value || value === '') {
              callback();
              return;
            }
            if (this.idCardType) {
              const reg = this.$validate.idCard;
              if (!reg.test(value)) {
                callback(new Error('请输入正确的身份证号码'));
              } else {
                callback();
              }
            } else {
              callback();
            }
          },
          trigger: 'change'
        }],
        nickname: [{
          required: true,
          message: '请输入姓名',
          trigger: 'blur'
        }],
        serialNumber: [{
          required: true,
          message: '请输入客户编码',
          trigger: 'blur'
        }],
        sex: [{
          required: true,
          message: '请选择性别',
          trigger: 'blur'
        }],
        medicalReport: [{
          required: true,
          message: '请选择是否有体检报告',
          trigger: 'blur'
        }],
        contagion: [{
          required: true,
          message: '请选择是否存在传染病',
          trigger: 'blur'
        }],
        address: [{
          required: true,
          message: '请输入居住地址',
          trigger: 'blur'
        }],
        birth: [{
          required: false
        }],
        phone: [{
          required: true,
          message: '请输入手机号码',
          trigger: 'blur'
        }, {pattern: this.$validate.mobilePhone, trigger: 'change', message: '请输入正确的手机号码'}]
      }
    }
  },
  created() {

  },
  computed: {},
  watch: {},
  methods: {
    add() {
      this.form = {}
      this.visible = true
      this.disabledType = false
      this.type = '1'
      this.fileList = []
    },
    edit(value) {
      this.form = {...value}
      this.visible = true
      this.disabledType = true
      this.type = '2'
      this.fileList = []
      this.$set(this.form, 'medicalReportList', this.form.medicalReport ? this.form.medicalReport.split(',') : [])
      console.log('edit', this.form.medicalReportList)
      if (this.form.reportFiles) {
        let uid = 1
        this.form.reportFiles.split(',').forEach(item => {
          this.fileList.push({
            uid: uid,
            name: item.split('/').pop(),
            status: 'done',
            url: item,
          })
          uid = uid + 1
        })
      }
      this.getAge(this.form.birth)
      this.fileUid = this.fileList.length + 1
    },
    resetPassword () {
      this.form.mmpd = this.form.idCard.slice(-6)
      console.log('resetPassword', this.form.mmpd)
    },
    changeIdType (e) {
      if (e.target.value === 'idCard') {
        this.idCardType = true
      } else {
        this.idCardType = false
      }
    },
    idCardChange () {
      // 如果不是身份证类型，则不进行处理
      if (!this.idCardType || this.type === '2') {
        return;
      }
      let value = this.form.idCard
      console.log('判断是否是身份证号码', this.form.idCard)
      // 判断是否是身份证号码
      if (this.$validate.idCard.test(value)) {
        // 获取出生日期和年龄
        let birthDateStr;

        // 15位身份证号码
        if (value.length === 15) {
          birthDateStr = `19${value.substr(6, 2)}-${value.substr(8, 2)}-${value.substr(10, 2)}`;
        }
        // 18位身份证号码
        else if (value.length === 18) {
          birthDateStr = `${value.substr(6, 4)}-${value.substr(10, 2)}-${value.substr(12, 2)}`;
        }
        this.$set(this.form, 'birth', birthDateStr);
        // 计算年龄
        if (birthDateStr) {
          const birthDate = new Date(birthDateStr);
          const today = new Date();

          let age = today.getFullYear() - birthDate.getFullYear();
          const monthDiff = today.getMonth() - birthDate.getMonth();

          // 如果今年生日还没过，年龄减1
          if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
            age--;
          }
          // 更新表单数据
          this.$set(this.form, 'age', age);
          this.$set(this.form, 'mmpd', value.substring(value.length - 6));
        }
      }
    },
    changeGender(e) {
      this.$set(this.form, 'sex', e.target.value)
    },
    changeMedicalReport(e) {
      console.log('changeMedicalReport', e)
      this.$set(this.form, 'medicalReportList', e)
      this.$set(this.form, 'medicalReport', e.join(','))
    },
    changeContagion(e) {
      this.$set(this.form, 'contagion', e.target.value)
    },
    onChangeBirth(date, dateString) {
      this.$set(this.form, 'birth', dateString)
      // 计算年龄 dateString:2025-07-20
      this.getAge(dateString)
    },
    getAge (dateString) {
      if (dateString) {
        const birthDate = new Date(dateString);
        const today = new Date();
        let age = today.getFullYear() - birthDate.getFullYear();
        const monthDiff = today.getMonth() - birthDate.getMonth();
        // Adjust age if birthday hasn't occurred yet this year
        if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
          age--;
        }
        this.$set(this.form, 'age', age);
      }
    },
    beforeUpload() {
      return false
    },
    handleRemove(file) {
      // 从fileList中移除该文件
      console.log('从fileList中移除该文件')
      const index = this.fileList.findIndex(item => item.uid === file.uid);
      if (index !== -1) {
        this.fileList.splice(index, 1);
        this.form.reportFiles = undefined
      }
    },
    // 上传
    async previewFile(file) {
      // 判断是否重复文件，是则从fileList中删除
      const index = this.fileList.findIndex(item => item.name === file.file.name);
      if (index !== -1) {
        this.fileList.splice(index, 1);
        this.form.reportFiles = this.fileList.map(item => item.url).join(',')
        return
      }
      this.uploadLoading = true
      const newFile = file.file
      const policy = await this.getSignature()
      console.log('policy', policy)
      // 暂时取消回调
      const audio = await this.postFile(newFile, policy)
      console.log('audio', audio)
      let audioFile = {
        uid: this.fileUid,
        name: audio.split('/').pop(),
        status: 'done',
        url: audio,
      }
      this.fileUid = this.fileUid + 1
      this.fileList.push(audioFile)
      // 上传完成后，更新form.reportFiles, this.fileList的name逗号分隔
      this.form.reportFiles = this.fileList.map(item => item.url).join(',')
      this.uploadLoading = false
    },
    // 获取签名
    getSignature() {
      const dir = 'user_medical_report' // 文件夹名称
      return new Promise((resolve, reject) => {
        this.$get(`${this.$api.system.file.getPolicy}?dir=${dir}`).then(res => {
          resolve(res.data)
        })
      })
    },
    // 调取文件上传
    postFile(file, policy) {
      const formData = new FormData()
      formData.append('name', file.name)
      formData.append('key', policy.dir + file.name)
      formData.append('policy', policy.policy)
      formData.append('OSSAccessKeyId', policy.accessid)
      formData.append('success_action_status', '200')
      formData.append('signature', policy.signature)
      formData.append('callback', policy.callback)
      formData.append('file', file)
      return new Promise(resolve => {
        const request = new XMLHttpRequest()
        request.open('POST', policy.host)
        request.send(formData)
        request.onreadystatechange = function () {
          console.log('request', request)
          if (request.status === 200) {
            // 4.2 打印服务器响应回来的数据
            console.log('request', request)
            const url = `${policy.host}/${policy.dir + file.name}`
            resolve(url)
          }
        }
      })
    },
    // 预览：图片和PDF弹窗预览，其他文件点击下载
    onPreview(file) {
      const url = file.url || (file.response && file.response.url) || ''
      if (!url) {
        return
      }
      const safeUrl = (url || '').split('#')[0]
      const fileName = file.name || safeUrl.split('/').pop() || ''
      const extFromUrl = safeUrl.indexOf('.') > -1 ? safeUrl.split('.').pop().toLowerCase() : ''
      const extFromName = fileName.indexOf('.') > -1 ? fileName.split('.').pop().toLowerCase() : ''
      const ext = extFromUrl || extFromName
      const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg']
      if (imageExts.includes(ext)) {
        this.previewType = 'image'
        this.previewUrl = url
        this.previewVisible = true
      } else if (ext === 'pdf') {
        this.previewType = 'pdf'
        // 将URL转换为PDF预览格式
        this.previewUrl = `https://mozilla.github.io/pdf.js/web/viewer.html?file=${encodeURIComponent(url)}`
        this.previewVisible = true
      } else {
        try {
          const a = document.createElement('a')
          a.href = url
          a.download = fileName || 'download'
          a.target = '_blank'
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
        } catch (e) {
          window.open(url, '_blank')
        }
      }
    }
  },
  mounted() {
  }
}
</script>

<style scoped>
.ry-modal .body-container .ant-form-item {
  margin-bottom: 0.05rem;
}
</style>
